<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="名称" prop="collegeName">
        <el-input
          v-model="queryParams.collegeName"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="collegePhone">
        <el-input
          v-model="queryParams.collegePhone"
          placeholder="请输入联系电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="详细地址" prop="collegeDetail">
        <el-input
          v-model="queryParams.collegeDetail"
          placeholder="请输入详细地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="cyan"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:college:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:college:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:college:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:college:export']"
          >导出</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:college:import']"
          >导入</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="collegeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="collegeCode" />
      <el-table-column label="名称" align="center" prop="collegeName" />
      <el-table-column label="联系电话" align="center" prop="collegePhone" />
      <el-table-column label="区域代码" align="center" prop="collegeAdcode" />
       <!-- <el-table-column label="校管理员" align="center" prop="collegeStaffName" /> -->
      <el-table-column
        label="状态"
        align="center"
        prop="collegeStatus"
        :formatter="collegeStatusFormat"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:college:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:college:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改院校对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
           <el-col :span="12">
            <el-form-item label="编号" prop="collegeCode">
              <el-input v-model="form.collegeCode" placeholder="请输入编号" />
            </el-form-item>
           </el-col>
             <el-col :span="12">
                 <el-form-item label="名称" prop="collegeName">
                  <el-input v-model="form.collegeName" placeholder="请输入名称" />
                </el-form-item>
           </el-col>
         </el-row>

         <el-row>
           <el-col :span="12">
              <el-form-item label="联系电话" prop="collegePhone">
                <el-input v-model="form.collegePhone" placeholder="请输入联系电话" />
              </el-form-item>
           </el-col>
             <el-col :span="12">
                 <el-form-item label="状态">
                  <el-radio-group v-model="form.collegeStatus">
                    <el-radio
                      v-for="dict in collegeStatusOptions"
                      :key="dict.dictValue" 
                      :label="parseInt(dict.dictValue)"
                      >{{ dict.dictLabel }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
                
           </el-col>
            
         </el-row>

          <el-row v-show="false"> 
           <el-col :span="12" >
               <el-form-item label="所在市" prop="collegeCity">
                <el-input v-model="form.collegeCity" placeholder="请输入所在市" />
              </el-form-item>
           </el-col>
              <el-col :span="12">
                <el-form-item label="所在区县" prop="collegeDistrict">
                  <el-input
                    v-model="form.collegeDistrict"
                    placeholder="请输入所在区县"
                  />
                </el-form-item>
           </el-col>
         </el-row>

          <el-row v-show="false"> 
           <el-col :span="12">
                <el-form-item label="所在乡镇" prop="collegeTownship">
                  <el-input
                    v-model="form.collegeTownship"
                    placeholder="请输入所在乡镇"
                  />
                </el-form-item>
           </el-col>
              <el-col :span="12">
                <el-form-item label="所在街道" prop="collegeStreet">
                  <el-input v-model="form.collegeStreet" placeholder="请输入所在街道" />
                </el-form-item>
           </el-col>
         </el-row>

          <el-row v-show="false">
           <el-col :span="12">
                  <el-form-item label="区域代码" prop="collegeAdcode">
                    <el-input v-model="form.collegeAdcode" placeholder="请输入区域代码" />
                  </el-form-item>
           </el-col>
             <el-col :span="12" v-show="false">
                <el-form-item label="所在省" prop="collegeProvince">
                  <el-input v-model="form.collegeProvince" placeholder="请输入所在省" />
                </el-form-item>
           </el-col>
         </el-row>
        <el-form-item label="详细地址" prop="collegeDetail">
          <el-input v-model="form.collegeDetail" placeholder="请输入详细地址" />
        </el-form-item>
        <!-- <el-form-item label="经纬度" prop="collegeLocation">
         <el-input v-model="form.collegeLocation" placeholder="请输入经纬度" />
        </el-form-item> -->
        <template lang="html">
        <div style="width:100%;height:500px;">
            <div class="container">
              <div class="search-box">
                <input
                  v-model="searchKey"
                  type="search"
                  id="search">
                <el-button @click="searchByHand" type="primary">搜索</el-button>
                <div class="tip-box" id="searchTip"></div>
              </div>
              <!--
                amap-manager： 地图管理对象
                vid：地图容器节点的ID
                zooms： 地图显示的缩放级别范围，在PC上，默认范围[3,18]，取值范围[3-18]；在移动设备上，默认范围[3-19]，取值范围[3-19]
                center： 地图中心点坐标值
                plugin：地图使用的插件
                events： 事件
              -->
              <el-amap class="amap-box"
                :amap-manager="amapManager"
                :vid="'amap-vue'"
                :zoom="zoom"
                :plugin="plugin"
                :center="center"
                :events="events"
              >
                <!-- 标记 -->
                <el-amap-marker v-for="(marker, index) in markers" :position="marker" :key="index"></el-amap-marker>
              </el-amap>
            </div>
        </div>
        </template>
        


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 学校导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox
            v-model="upload.updateSupport"
          />是否更新已经存在的院校数据
          <el-link type="info" style="font-size: 12px" @click="importTemplate"
            >下载模板</el-link
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>



<script>
import { AMapManager, lazyAMapApiLoaderInstance } from 'vue-amap'
import {
  listCollege,
  getCollege,
  delCollege,
  addCollege,
  updateCollege,
  exportCollege,
  importTemplate,
  getStaff,
  MP,
} from "@/api/system/college";
import { getToken } from "@/utils/auth";
let amapManager = new AMapManager()
export default {
  name:'AMap',
  data() {
    let self = this
    return {
       // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 院校表格数据
      collegeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      collegeStatusOptions: [],
      // 删除位字典
      collegeIsDeleteOptions: [],
      //校管数据
      options:[],
      // 学校导入参数
      upload: {
        // 是否显示弹出层（学校导入）
        open: false,
        // 弹出层标题（学校导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的学校数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/college/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        collegeName: null,
        collegePhone: null,
        collegeDetail: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        collegeCode: [
          { required: true, message: "编号不能为空", trigger: "blur" },
        ],
        collegeName: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
        collegePhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
        ],
        collegeAdcode: [
          { required: true, message: "区域代码不能为空", trigger: "blur" },
        ],
         
        collegeStatus: [
          { required: true, message: "状态不能为空", trigger: "blur" },
        ],
      },
      address: null,
      searchKey: '',
      amapManager,
      markers: [],
      searchOption: {
        city: '全国',
        citylimit: true
      },
      center: [115.749914,28.67495],
      zoom: 17,
      lng: 0,
      lat: 0,
      loaded: false,
      events: {
        init() {
          lazyAMapApiLoaderInstance.load().then(() => {
            self.initSearch()
          })
        },
        // 点击获取地址的数据
        click(e) {
          self.markers = []
          let { lng, lat } = e.lnglat
          self.lng = lng
          self.lat = lat
          self.center = [lng, lat]
          self.markers.push([lng, lat])
          // 这里通过高德 SDK 完成。
          let geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          })
          geocoder.getAddress([lng, lat], function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                console.log(result.regeocode.formattedAddress) //控制台打印地址
                //saveFrom(result,lng,lat);
                let locatin = "("+lng+","+lat+")";
                self.form.collegeLocation = locatin;
                self.form.collegeDetail = result.regeocode.formattedAddress;
                self.form.collegeProvince = result.regeocode.addressComponent.province;
                self.form.collegeCity = result.regeocode.addressComponent.city;
                self.form.collegeDistrict = result.regeocode.addressComponent.district;
                self.form.collegeAdcode = result.regeocode.addressComponent.adcode;
                self.form.collegeTownship= result.regeocode.addressComponent.township;
                self.form.collegeStreet= result.regeocode.addressComponent.street;
                self.address = result.regeocode.formattedAddress
                self.searchKey = result.regeocode.formattedAddress
                self.$nextTick()
              }
            }
          })
        }
      },
      // 一些工具插件
      plugin: [
        {
          pName: 'Geocoder',
          events: {
            init (o) {
              //console.log("一些工具插件--地址"+o.getAddress())
            }
          }
        },
        {
          // 定位
          pName: 'Geolocation',
          events: {
            init(o) {
              // o是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  // 设置经度
                  self.lng = result.position.lng
                  // 设置维度
                  self.lat = result.position.lat
                  // 设置坐标
                  self.center = [self.lng, self.lat]
                  self.markers.push([self.lng, self.lat])
                  // load
                  self.loaded = true
                  // 页面渲染好后
                  self.$nextTick()
                }
              })
            }
          }
        },
        {
          // 工具栏
          pName: 'ToolBar',
          events: {
            init(instance) {
               //console.log("工具栏:"+instance);
            }
          }
        },
        {
          // 鹰眼
          pName: 'OverView',
          events: {
            init(instance) {
               //console.log("鹰眼:"+instance);
            }
          }
        },
        {
          // 地图类型
          pName: 'MapType',
          defaultType: 0,
          events: {
            init(instance) {
               //console.log("地图类型:"+instance);
            }
          }
        },
        {
          // 搜索
          pName: 'PlaceSearch',
          events: {
            init(instance) {
               //console.log("搜索:"+instance)
            }
          }
        }
      ]
    }
  },
  created() {
    this.getList();
    // 验证用户是否具备某角色var role = [[${@permission.hasRole('admin')}]];
    this.getDicts("sys_job_status").then((response) => {
      this.collegeStatusOptions = response.data;
    });
    this.getDicts("student_delete").then((response) => {
      this.collegeIsDeleteOptions = response.data;
    });
  },
  methods: {
    saveFrom(result,lng, lat){
                _this.form.collegeLocation = (lng, lat);
                _this.form.collegeDetail = result.regeocode.formattedAddress;
                _this.form.collegeProvince = result.regeocode.addressComponent.province;
                _this.form.collegeCity = result.regeocode.addressComponent.city;
                _this.form.collegeDistrict = result.regeocode.addressComponent.district;
                _this.form.collegeAdcode = result.regeocode.addressComponent.adcode;
    },
    initSearch() {
      let vm = this
      let map = this.amapManager.getMap()
      AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {
        var poiPicker = new PoiPicker({
          input: 'search',
          placeSearchOptions: {
            map: map,
            pageSize: 10
          },
          suggestContainer: 'searchTip',
          searchResultsContainer: 'searchTip'
        })
        vm.poiPicker = poiPicker
        // 监听poi选中信息
        poiPicker.on('poiPicked', function(poiResult) {
           let source = poiResult.source
           let poi = poiResult.item
           if (source !== 'search') {
             poiPicker.searchByKeyword(poi.name)
           } else {
             poiPicker.clearSearchResults()
             vm.markers = []
             let lng = poi.location.lng
             let lat = poi.location.lat
             let address = poi.cityname + poi.adname + poi.name
             vm.center = [lng, lat]
             vm.markers.push([lng, lat])
             vm.lng = lng
             vm.lat = lat
             vm.address = address
             vm.searchKey = address
          let geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          })
          geocoder.getAddress([lng, lat], function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                console.log(result.regeocode.formattedAddress) //控制台打印地址
                //saveFrom(result,lng,lat);
                let locatin = "("+lng+","+lat+")";
                vm.form.collegeLocation = locatin;
                vm.form.collegeDetail = result.regeocode.formattedAddress;
                vm.form.collegeProvince = result.regeocode.addressComponent.province;
                vm.form.collegeCity = result.regeocode.addressComponent.city;
                vm.form.collegeDistrict = result.regeocode.addressComponent.district;
                vm.form.collegeAdcode = result.regeocode.addressComponent.adcode;
                vm.form.collegeTownship= result.regeocode.addressComponent.township;
                vm.form.collegeStreet= result.regeocode.addressComponent.street;
                vm.address = result.regeocode.formattedAddress
                vm.searchKey = result.regeocode.formattedAddress
                vm.$nextTick()
              }
            }
          })

           }
        })
      })
    },
    searchByHand() {
      console.log("123123123123123123123"+this.searchKey);
      if (this.searchKey !== '') {
        this.poiPicker.searchByKeyword(this.searchKey)
      }
    },
      /** 查询院校列表 */
    getList() {
      this.loading = true;
      listCollege(this.queryParams).then((response) => {
        this.collegeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 状态字典翻译
    collegeStatusFormat(row, column) {
      return this.selectDictLabel(this.collegeStatusOptions, row.collegeStatus);
    },
    // 删除位字典翻译
    collegeIsDeleteFormat(row, column) {
      return this.selectDictLabel(
        this.collegeIsDeleteOptions,
        row.collegeIsDelete
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        collegeId: null,
        collegeCode: null,
        collegeName: null,
        collegePhone: null,
        collegeProvince: null,
        collegeCity: null,
        collegeDistrict: null,
        collegeTownship: null,
        collegeStreet: null,
        collegeDetail: null,
        collegeAdcode: null,
        collegeLocation: null,
        collegeStatus: 0,
        collegeCreateDt: null,
        collegeModifyDt: null,
        collegeIsDelete: null,
      };
      this.resetForm("form");
      this.searchKey = '';
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.collegeId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加院校";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const collegeId = row.collegeId || this.ids;
      getCollege(collegeId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改院校";
        //获取学校管理员列表
        // getStaff(collegeId).then((response) => {
        //    this.options = response.rows
        //  });
    })},
    

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.collegeId != null) {
            updateCollege(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addCollege(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功--已默认添加校管");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const collegeName = row.collegeName;
      const ids = row.collegeId || this.ids;
      console.log("12312312312312____:"+ids);
      this.$confirm(
        '是否确认删除院校为"' + collegeName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delCollege(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有院校数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportCollege(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () {});
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "学校导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
}
</script>

<style lang="css">
.container {
  width: 100%;
  height: 100%;
  position: relative;
  left: 50%;
  top: 50%;
  transform: translate3d(-50%, -50%, 0);
  border: 1px solid #999;
}
.search-box {
  position: absolute;
  z-index: 5;
  width: 30%;
  left: 13%;
  top: 10px;
  height: 30px;
}
.search-box input {
  float: left;
  width: 80%;
  height: 100%;
  border: 1px solid #30ccc1;
  padding: 0 8px;
  outline: none;
}
.search-box button {
  float: left;
  width: 20%;
  height: 100%;
  background: #30ccc1;
  border: 1px solid #30ccc1;
  color: #fff;
  outline: none;
}
.tip-box {
  width: 100%;
  max-height: 260px;
  position: absolute;
  top: 30px;
  overflow-y: auto;
  background-color: #fff;
}
</style>
